<html>
<head><title>Web Query Interface</title></head>

<body>
<h1>Movies Database Query Interface</h1>

<p>Please enter your query here</p>
Type an MySQL query in the following box:
<p>
<form action="query.php" method="GET">
<textarea name="query" cols="60" rows="8"></textarea>
<input type="submit" value="Submit" />
</form>
</p>

<?php

//get input
$oldInput = $_GET["query"];

//if there is input, execute php code
if($oldInput)
{

print "<h2>Results from MySQL Query:</h2>";

//connect to the database
$db_connection = @mysql_connect("localhost", "cs143", "");
$db_select = @mysql_select_db("CS143", $db_connection);

//if a connection could not be set
if(!$db_connection)
{
  echo "<h3>Could not connect to database.</h3><b><u>Error:</u></b> " . mysql_error() . "<br />";
  exit(1);
}
//if the database could be accessed
elseif(!$db_select)
{
  echo "<h3>Could not select database.</h3><b><u>Error:</u></b> " . mysql_error() . "<br />";
  exit(1);
}
//the connection and database were set
else
{

$input = $oldInput;

//execute the query
$result = false;
$result = @mysql_query($input, $db_connection);

//the query failed
if(!$result)
{
  echo "<h3>Invalid MySQL Query.</h3><b><u>Invalid Input:</u></b> " . $input;
}
//the query executed successfully
else
{

echo "<p><b><u>Your MySQL Query:</u></b><br />" . $input . "</p>";

//if an insert/update/delete or other modification statement was used
//mysql_query returns a boolean value
//report number of rows affected
if(is_bool($result))
  echo "Query OK, " . mysql_affected_rows($db_connection) . " row(s) affected.";
//the query returned a table
//mysql_query returns a resource value
else
{

$numFields = mysql_num_fields($result);

//Set up table to display results
echo "<table border=1 cellspacing=1 cellpadding=2><tr align=center>";

//Write out field names
for($i = 0; $i<$numFields; $i++)
  echo "<th>" . mysql_field_name($result, $i) . "</th>";

echo "</tr>";

//Write out each row
while($row = mysql_fetch_row($result))
{
  echo "<tr align=center>";
  for($i = 0; $i<$numFields; $i++)
  {
	echo "<td>";
        $current = $row[$i];
        if ($current == NULL)
		print "N/A";
	else
		print $current;
	echo "</td>";
  }
  echo "</tr>";
}

echo "</table>";
}

}

//close the database connection
mysql_close($db_connection);

}
}

?>


</body>

</html>

